const Group = require('../models/groupModel');
const User = require('../models/userModel');

const createGroup = (req, res) => {
  const { name, creatorId } = req.body;

  Group.create(name, creatorId, (err, groupId) => {
    if (err) {
      return res.status(500).json({ error: 'Database error' });
    }
    res.status(201).json({ groupId, message: 'Group created successfully' });
  });
};

const addMember = (req, res) => {
  const { groupId } = req.params;
  const { userId } = req.body;

  Group.addMember(groupId, userId, (err) => {
    if (err) {
      return res.status(500).json({ error: 'Database error' });
    }
    res.json({ message: 'User added to group successfully' });
  });
};

const sendMessage = (req, res) => {
  const { groupId } = req.params;
  const { senderId, message } = req.body;

  // 更新发送者的最后活跃时间
  User.updateLastActive(senderId, (err) => {
    if (err) {
      console.error('Error updating last active:', err);
    } else {
      console.log(`User ${senderId} last active time updated`);
    }
  });

  Group.sendMessage(groupId, senderId, message, (err, messageId) => {
    if (err) {
      return res.status(500).json({ error: 'Database error' });
    }
    res.json({ messageId, message: 'Message sent successfully' });
  });
};

const getMessages = (req, res) => {
  const { groupId } = req.params;

  Group.getMessages(groupId, (err, messages) => {
    if (err) {
      return res.status(500).json({ error: 'Database error' });
    }
    res.json(messages);
  });
};

const getUserGroups = (req, res) => {
  const { userId } = req.params;

  Group.getUserGroups(userId, (err, groups) => {
    if (err) {
      return res.status(500).json({ error: 'Database error' });
    }
    res.json(groups);
  });
};

module.exports = { createGroup, addMember, sendMessage, getMessages, getUserGroups }; 